const hotwords = JSON.stringify({
  你好飞飞: 100
})

function WebSocketConnectMethod(url, store) {
  // store：Vuex 实例
  let speechSokt
  let reconnectAttempts = 0
  const MAX_RECONNECT_ATTEMPTS = 5
  const RECONNECT_DELAY = 3000 // 3秒后重连

  this.wsStart = function () {
    if ('WebSocket' in window) {
      connect()
      return 1
    } else {
      alert('当前浏览器不支持 WebSocket')
      return 0
    }
  }

  const connect = () => {
    speechSokt = new WebSocket(url)
    speechSokt.onopen = onOpen
    speechSokt.onclose = onClose
    speechSokt.onmessage = onMessage
    speechSokt.onerror = onError
  }

  const reconnect = () => {
    if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
      reconnectAttempts++
      console.log(
        `尝试重连... (${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`
      )
      setTimeout(() => {
        connect()
      }, RECONNECT_DELAY)
    } else {
      console.log('达到最大重连次数，停止重连')
      store.dispatch('stateHandle', 2) // 通知状态为错误
    }
  }

  this.wsStop = function () {
    if (speechSokt != undefined) {
      console.log('stop ws!')
      speechSokt.close()
    }
  }

  this.wsSend = function (oneData) {
    if (!speechSokt) return
    if (speechSokt.readyState === 1) {
      speechSokt.send(oneData)
    }
  }

  this.resetRecognition = function () {
    if (speechSokt && speechSokt.readyState === 1) {
      const endRequest = {
        is_speaking: false
      }
      speechSokt.send(JSON.stringify(endRequest))
      console.log('发送结束当前识别会话信号')

      setTimeout(() => {
        const startRequest = {
          chunk_size: [5, 10, 5],
          hotwords: hotwords,
          wav_name: 'h5',
          is_speaking: true,
          chunk_interval: 10,
          itn: true,
          mode: '2pass-offline',
          audio_fs: 16000,
          audio_format: 'wav'
        }
        speechSokt.send(JSON.stringify(startRequest))
        console.log('发送开始新识别会话信号')
      }, 300)

      return true
    }
    return false
  }

  function onOpen() {
    reconnectAttempts = 0
    const request = {
      chunk_size: [5, 10, 5],
      hotwords: hotwords,
      wav_name: 'h5',
      is_speaking: true,
      chunk_interval: 10,
      itn: true,
      mode: '2pass-offline',
      audio_fs: 16000,
      audio_format: 'wav'
    }

    // console.log('发送初始配置:', JSON.stringify(request, null, 2))
    speechSokt.send(JSON.stringify(request))
    console.log('连接成功')

    store.dispatch('stateHandle', 1)
  }

  function onClose(e) {
    console.log('连接关闭!', e)
    store.dispatch('stateHandle', 0)

    if (e.code !== 1000) {
      reconnect()
    }
  }

  function onMessage(e) {
    try {
      const data = JSON.parse(e.data)

      if (data.stamp_sents) {
        store.dispatch('msgHandle', data.text)
      }
    } catch (error) {
      console.error('解析消息失败：', error)
    }
  }

  function onError(e) {
    console.log('连接错误!', e)
    store.dispatch('stateHandle', 2)
    reconnect()
  }
}

export default WebSocketConnectMethod
